<template>
  <div class="dashboard">
    <div class="container mx-auto px-4 py-8">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-900">仪表板</h1>
        <p class="text-gray-600 mt-2">实时监控系统数据和业务指标</p>
      </div>

      <!-- 概览统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div v-for="stat in overviewStats" :key="stat.title" 
             class="bg-white rounded-lg shadow-md p-6 border border-gray-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm font-medium text-gray-600">{{ stat.title }}</p>
              <p class="text-2xl font-bold text-gray-900">{{ stat.value }}</p>
              <p class="text-sm text-green-600 mt-1">
                <span v-if="stat.growth > 0">+</span>{{ stat.growth }}% 较上月
              </p>
            </div>
            <div class="p-3 bg-blue-100 rounded-full">
              <component :is="stat.icon" class="w-6 h-6 text-blue-600" />
            </div>
          </div>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
        <!-- 销售趋势图 -->
        <div class="bg-white rounded-lg shadow-md p-6 border border-gray-200">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">销售趋势</h3>
          <div class="h-64 flex items-end justify-between space-x-2">
            <div v-for="(item, index) in salesTrend" :key="index" 
                 class="flex-1 bg-blue-500 rounded-t" 
                 :style="{ height: `${(item.sales / maxSales) * 100}%` }">
            </div>
          </div>
          <div class="flex justify-between text-sm text-gray-600 mt-2">
            <span>{{ salesTrend[0]?.date }}</span>
            <span>{{ salesTrend[salesTrend.length - 1]?.date }}</span>
          </div>
        </div>

        <!-- 用户增长图 -->
        <div class="bg-white rounded-lg shadow-md p-6 border border-gray-200">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">用户增长</h3>
          <div class="h-64 flex items-end justify-between space-x-2">
            <div v-for="(item, index) in userGrowth" :key="index" 
                 class="flex-1 bg-green-500 rounded-t" 
                 :style="{ height: `${(item.users / maxUsers) * 100}%` }">
            </div>
          </div>
          <div class="flex justify-between text-sm text-gray-600 mt-2">
            <span>{{ userGrowth[0]?.date }}</span>
            <span>{{ userGrowth[userGrowth.length - 1]?.date }}</span>
          </div>
        </div>
      </div>

      <!-- 热门商品和最近订单 -->
      <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <!-- 热门商品 -->
        <div class="bg-white rounded-lg shadow-md p-6 border border-gray-200">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">热门商品</h3>
          <div class="space-y-4">
            <div v-for="product in topProducts" :key="product.id" 
                 class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
              <div>
                <p class="font-medium text-gray-900">{{ product.name }}</p>
                <p class="text-sm text-gray-600">销量: {{ product.sales }} | 收入: ¥{{ formatPrice(product.revenue) }}</p>
              </div>
              <span class="text-sm text-green-600">+{{ product.growth }}%</span>
            </div>
          </div>
        </div>

        <!-- 最近订单 -->
        <div class="bg-white rounded-lg shadow-md p-6 border border-gray-200">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">最近订单</h3>
          <div class="space-y-4">
            <div v-for="order in recentOrders" :key="order.id" 
                 class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
              <div>
                <p class="font-medium text-gray-900">{{ order.customer }}</p>
                <p class="text-sm text-gray-600">{{ order.product }}</p>
                <p class="text-xs text-gray-500">{{ formatDate(order.date) }}</p>
              </div>
              <div class="text-right">
                <p class="font-medium text-gray-900">¥{{ formatPrice(order.amount) }}</p>
                <span :class="getStatusClass(order.status)" class="text-xs px-2 py-1 rounded-full">
                  {{ getStatusText(order.status) }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// 图标组件
const UserIcon = defineComponent({
  template: '<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path></svg>'
})

const ShoppingCartIcon = defineComponent({
  template: '<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4m0 0L7 13m0 0l-2.5 5M7 13l2.5 5m6-5v6a2 2 0 01-2 2H9a2 2 0 01-2-2v-6m8 0V9a2 2 0 00-2-2H9a2 2 0 00-2 2v4.01"></path></svg>'
})

const CurrencyDollarIcon = defineComponent({
  template: '<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1"></path></svg>'
})

const CubeIcon = defineComponent({
  template: '<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path></svg>'
})

// 响应式数据
const dashboardData = ref(null)
const loading = ref(true)

// 计算属性
const overviewStats = computed(() => {
  if (!dashboardData.value) return []
  
  const { overview } = dashboardData.value
  return [
    {
      title: '总用户数',
      value: overview.totalUsers.toLocaleString(),
      growth: overview.userGrowth,
      icon: UserIcon
    },
    {
      title: '总订单数',
      value: overview.totalOrders.toLocaleString(),
      growth: overview.revenueGrowth,
      icon: ShoppingCartIcon
    },
    {
      title: '总收入',
      value: `¥${formatPrice(overview.totalRevenue)}`,
      growth: overview.revenueGrowth,
      icon: CurrencyDollarIcon
    },
    {
      title: '商品总数',
      value: overview.totalProducts.toLocaleString(),
      growth: 5.2,
      icon: CubeIcon
    }
  ]
})

const salesTrend = computed(() => dashboardData.value?.salesTrend || [])
const userGrowth = computed(() => dashboardData.value?.userGrowth || [])
const topProducts = computed(() => dashboardData.value?.topProducts || [])
const recentOrders = computed(() => dashboardData.value?.recentOrders || [])

const maxSales = computed(() => Math.max(...salesTrend.value.map(item => item.sales)))
const maxUsers = computed(() => Math.max(...userGrowth.value.map(item => item.users)))

// 方法
const formatPrice = (price) => {
  return (price / 1000).toFixed(1) + 'k'
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const getStatusClass = (status) => {
  const classes = {
    delivered: 'bg-green-100 text-green-800',
    shipped: 'bg-blue-100 text-blue-800',
    processing: 'bg-yellow-100 text-yellow-800',
    pending: 'bg-gray-100 text-gray-800',
    cancelled: 'bg-red-100 text-red-800'
  }
  return classes[status] || 'bg-gray-100 text-gray-800'
}

const getStatusText = (status) => {
  const texts = {
    delivered: '已送达',
    shipped: '已发货',
    processing: '处理中',
    pending: '待处理',
    cancelled: '已取消'
  }
  return texts[status] || status
}

// 获取数据
const fetchDashboardData = async () => {
  try {
    loading.value = true
    const response = await $fetch('/api/dashboard')
    dashboardData.value = response.data
  } catch (error) {
    console.error('获取仪表板数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchDashboardData()
})
</script>

<style scoped>
.dashboard {
  min-height: 100vh;
  background-color: #f8fafc;
}
</style> 